package com.casstime.ec.cloud.discount.services;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.casstime.commons.utils.IncrementIdCreator;
import com.casstime.ec.cloud.discount.dao.gift.GiftProductImageMapper;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionAreaMapper;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionFlowingMapper;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionGiftMapper;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionMapper;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionProductMapper;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionUpdateRecordMapper;
import com.casstime.ec.cloud.discount.model.AmountOrderInfo;
import com.casstime.ec.cloud.discount.model.DiscountRuleParam;
import com.casstime.ec.cloud.user.spi.models.User;
import com.casstime.ec.cloud.values.amountPromotion.AmountPromotionQueryRequest;
import com.casstime.ec.cloud.values.amountPromotion.enums.DiscountConfigValueEnum;
import com.casstime.ec.cloud.values.giftPromotion.GiftDeduction;
import com.casstime.ec.cloud.values.giftPromotion.GiftDeductionGift;
import com.casstime.ec.cloud.values.giftPromotion.GiftDeductionProduct;
import com.casstime.ec.cloud.values.giftPromotion.GiftProductImage;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotion;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionArea;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionFlowing;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionGift;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionGiftVO;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionProduct;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionRequest;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionUpdateRecord;
import com.casstime.ec.cloud.values.giftPromotion.enums.GiftConfigValueEnum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * ClassName: DiscountServiceImpl 
 * Function: (买赠促销数据实现类)
 * Reason: ADD REASON(可选).
 *  
 * @author wu.chen 
 * 2018年2月26日 上午11:02:13
 * @version   
 * @since JDK 1.8
 */
@Service
public class GiftPromotionDAOService {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private GiftPromotionMapper giftPromotionMapper;
	
	@Autowired
	private GiftPromotionUpdateRecordMapper updateRecordMapper;
	
	@Autowired
	private GiftPromotionProductMapper giftPromotionProductMapper;
	
	@Autowired
	private GiftPromotionGiftMapper giftPromotionGiftMapper;
	
	@Autowired
	private GiftPromotionAreaMapper giftPromotionAreaMapper;
	
	@Autowired
	private GiftProductImageMapper giftProductImageMapper;
	
	@Autowired
	private GiftPromotionFlowingMapper giftPromotionFlowingMapper;
	
	public int addGiftPromotion(GiftPromotion giftPromotion, User user) {
		IncrementIdCreator idCreator = new IncrementIdCreator();
		Date now = new Date();
		
		//生成首字母加时间的Id
		SimpleDateFormat simpleformat = new SimpleDateFormat("yyyyMMddHHmmss");
		HanyuPinyinOutputFormat pinyinFormat = new HanyuPinyinOutputFormat();
		pinyinFormat.setToneType(HanyuPinyinToneType.WITH_TONE_NUMBER);
		pinyinFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
		char[] arr = giftPromotion.getPromotionName().toCharArray(); 
		StringBuffer promotionId = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
	         if (arr[i] > 128) { 
                 try {   
                     String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], pinyinFormat);   
                     if (temp != null) {   
                    	 promotionId.append(temp[0].charAt(0));   
                     }   
                 } catch (BadHanyuPinyinOutputFormatCombination e) {   
                         logger.error("拼音转化失败{}", arr[i], e);
                 }
	         } else {   
	        	 promotionId.append(arr[i]);   
	         }   
		}
		promotionId.append(simpleformat.format(now));
		
		giftPromotion.setPromotionCode(promotionId.toString());
		giftPromotion.setId(idCreator.getNextIncrementId());
		giftPromotion.setLastUpdatedBy(user.getUserLoginId());
		giftPromotion.setLastUpdatedStamp(now);
		giftPromotion.setPromotionStatus("Y");
		
		int ret = giftPromotionMapper.insertOrUpdateGiftPromotion(giftPromotion);
		if (ret > 0) {
			insertPromotionConfigs(giftPromotion, idCreator, user, now);
			List<GiftPromotionUpdateRecord> records = Lists.newArrayList();
			GiftPromotionUpdateRecord record = new GiftPromotionUpdateRecord();
			record.setId(idCreator.getNextIncrementId());
			record.setPromotionId(giftPromotion.getId());
			record.setUserLoginId(user.getUserLoginId());
			record.setUserLoginName(user.getUserName());
			record.setCreatedStamp(now);
			record.setDescription(MessageFormat.format("新增 买赠优惠活动： {0}", giftPromotion.getPromotionName()));
			records.add(record);
			updateRecordMapper.insertGiftPromotionRecords(records);
			return 1;
		} else {
			return 0;
		}
	}
	
	public int updateGiftPromotion(GiftPromotion giftPromotion, User user) {
		IncrementIdCreator idCreator = new IncrementIdCreator();
		Date now = new Date();
		giftPromotion.setLastUpdatedBy(user.getUserLoginId());
		GiftPromotion oldPromotion = findGiftPromotion(giftPromotion.getId());
		List<String> promotionIds = Lists.newArrayList();
		promotionIds.add(oldPromotion.getId());
		oldPromotion.setAreas(giftPromotionAreaMapper.listPromotionAreas(promotionIds));
		oldPromotion.setGitfs(giftPromotionGiftMapper.listPromotionGifts(promotionIds));
		oldPromotion.setProducts(giftPromotionProductMapper.listPromotionProducts(promotionIds));
		if (CollectionUtils.isNotEmpty(oldPromotion.getGitfs()) && CollectionUtils.isNotEmpty(giftPromotion.getGitfs())) {
			for (GiftPromotionGift newGift : giftPromotion.getGitfs()) {
				for (GiftPromotionGift oldGift : oldPromotion.getGitfs()) {
					if (newGift.getGiftId().equals(oldGift.getGiftId())) {
						newGift.setExcessAmount(oldGift.getExcessAmount());
					}
				}
			}
		}
		
		int ret = giftPromotionMapper.insertOrUpdateGiftPromotion(giftPromotion);
		if (ret > 0) {
			giftPromotionMapper.deleteGiftPromotionById(giftPromotion.getId());
			insertPromotionConfigs(giftPromotion, idCreator, user, now);
			List<GiftPromotionUpdateRecord> records = Lists.newArrayList();
			GiftPromotionUpdateRecord record = createUpdateRecord(oldPromotion, giftPromotion, idCreator, user, now);
			if (record != null) {
				if (StringUtils.isNotBlank(record.getDescription()) && record.getDescription().length() > 1000) {
					record.setDescription(record.getDescription().substring(0, 1000));
				}
				records.add(record);
				updateRecordMapper.insertGiftPromotionRecords(records);
			}
			return 1;
		} else {
			return 0;
		}
	}
	
	public GiftPromotion findGiftPromotion(String promotionId) {
		GiftPromotion promotion = giftPromotionMapper.findGiftPromotionById(promotionId);
		if (promotion == null) {
			return null;
		}
		List<String> promotionIds = Lists.newArrayList();
		promotionIds.add(promotion.getId());
		promotion.setAreas(giftPromotionAreaMapper.listPromotionAreas(promotionIds));
		promotion.setGitfs(giftPromotionGiftMapper.listPromotionGifts(promotionIds));
		promotion.setProducts(giftPromotionProductMapper.listPromotionProducts(promotionIds));
		return promotion;
	}
	
	 public Page<GiftPromotionProduct> listGiftPromotionProductsById(String promotionId, Integer pageSize, Integer pageNum) {
			Page<GiftPromotionProduct> pagedResult = PageHelper.startPage(pageNum, pageSize);
			giftPromotionProductMapper.listGiftPromotionProductsById(promotionId);
			return pagedResult;
	 }
	
	/**
	 * findGiftPromotionProductByProductIds:(根据商品ID查询赠品相关信息).<br/>  
	 * @return
	 * @author 徐彪
	 * @date 2018年3月23日 上午11:30:12
	 */
	public List<GiftPromotionGiftVO> findGiftPromotionProductByProductIds(AmountPromotionQueryRequest queryRequest, 
			List<DiscountRuleParam> ruleParams) {
		List<GiftPromotionGiftVO> voList = Lists.newArrayList();
		List<String> productIds = queryRequest.getProductIds();
		//根据商品ID查询买赠活动Id
		List<GiftPromotionProduct> giftPromotionProducts = giftPromotionProductMapper.listPromotionProductsByProductIds(productIds);
		List<String> giftPromotionIds = giftPromotionProducts.stream().map(GiftPromotionProduct::getGiftPromotionId).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(giftPromotionIds)) {
			return Lists.newArrayList();
		}
		Map<String, String> mapId = Maps.newHashMap();
		for (String productId : productIds) {
			for (GiftPromotionProduct giftPromotionProduct : giftPromotionProducts) {
				if (productId.equals(giftPromotionProduct.getProductId())) {
					mapId.put(productId, giftPromotionProduct.getGiftPromotionId());
				}
			}
		}
		//通过giftPromotionIds取活动配置并过滤
        List<GiftPromotion> listGiftPromotion = filterGiftPromotion(giftPromotionIds, queryRequest, ruleParams);
        if (CollectionUtils.isEmpty(listGiftPromotion)) {
        	return Lists.newArrayList();
        }
        List<String> giftPromotionIdsFilter = listGiftPromotion.stream().map(GiftPromotion::getId).collect(Collectors.toList());
		//根据买赠活动ID查询赠品列表(一个买赠活动对应多个赠品)
		List<GiftPromotionGift> promotionGifts = giftPromotionGiftMapper.listPromotionGifts(giftPromotionIdsFilter);
		//过滤库存不足的赠品活动
		List<GiftPromotionGift> giftPromotionGifts = promotionGifts.stream().
				filter(p -> (p.getTotalAmount() - p.getExcessAmount()) > 0).collect(Collectors.toList());
		Map<String, List<GiftPromotionGift>> gpgListMap = Maps.newHashMap();
		for (GiftPromotionGift giftPromotionGift : giftPromotionGifts) {
			if (gpgListMap.containsKey(giftPromotionGift.getGiftPromotionId())) {
				gpgListMap.get(giftPromotionGift.getGiftPromotionId()).add(giftPromotionGift);
			} else {
				List<GiftPromotionGift> giftList = Lists.newArrayList();
				giftList.add(giftPromotionGift);
				gpgListMap.put(giftPromotionGift.getGiftPromotionId(), giftList);
			}
		}
		
		//拼装数据gpListMap,key为productId,value为List<GiftPromotionGift>
		Map<String, List<GiftPromotionGift>> gpListMap = Maps.newHashMap();
		for (Map.Entry<String, String> map : mapId.entrySet()) {
			for (Map.Entry<String, List<GiftPromotionGift>> gpgmap : gpgListMap.entrySet()) {
				if (map.getValue().equals(gpgmap.getKey())) {
					gpListMap.put(map.getKey(), gpgmap.getValue());
				}
			}
		} 
		GiftPromotionGiftVO vo = null;
		for (Map.Entry<String, List<GiftPromotionGift>> gpMap : gpListMap.entrySet()) {
			vo = new GiftPromotionGiftVO();
			vo.setId(gpMap.getKey());
			vo.setGiftProductGifts(gpMap.getValue());
			voList.add(vo);
		}
		List<String> giftIds = Lists.newArrayList();
		for (int i = 0; i < voList.size(); i++) {
			for (int j = 0; j < voList.get(i).getGiftProductGifts().size(); j++) {
				giftIds.add(voList.get(i).getGiftProductGifts().get(j).getGiftId());
			}
		}
		List<GiftProductImage> images = giftProductImageMapper.listGiftProductImages(giftIds);
		Map<String, List<GiftProductImage>> gpiListMap = Maps.newHashMap();
		for (GiftProductImage image : images) {
			if (gpiListMap.containsKey(image.getGiftId())) {
				gpiListMap.get(image.getGiftId()).add(image);
			} else {
				List<GiftProductImage> giftImageList = Lists.newArrayList();
				giftImageList.add(image);
				gpiListMap.put(image.getGiftId(), giftImageList);
			}
		}
		
		for (Map.Entry<String, List<GiftProductImage>> gpimap : gpiListMap.entrySet()) {
			for (int i = 0; i < voList.size(); i++) {
				for (int j = 0; j < voList.get(i).getGiftProductGifts().size(); j++) {
					if (voList.get(i).getGiftProductGifts().get(j).getGiftId().equals(gpimap.getKey())) {
						voList.get(i).getGiftProductGifts().get(j).setImages(gpimap.getValue());
					}
				}
			}
		}
		return voList;
	}
	
	public int stopGiftPromotion(String promotionId, User user) {
		int ret = giftPromotionMapper.updateGiftPromotionStatus(promotionId, "N");
		if (ret > 0) {
			GiftPromotionUpdateRecord record = new GiftPromotionUpdateRecord();
			record.setId(new IncrementIdCreator().getNextIncrementId());
			record.setPromotionId(promotionId);
			record.setUserLoginId(user.getUserLoginId());
			record.setUserLoginName(user.getUserName());
			record.setCreatedStamp(new Date());
			record.setDescription("活动状态修改为 停止活动；");
			List<GiftPromotionUpdateRecord> records = Lists.newArrayList();
			records.add(record);
			updateRecordMapper.insertGiftPromotionRecords(records);
		}
		return ret;
	}
	
	public Page<GiftPromotion> listGiftPromotionStoreId(String productStoreId, Integer pageSize, Integer pageNum,
			GiftPromotionRequest request) {
		Page<GiftPromotion> pagedResult = PageHelper.startPage(pageNum, pageSize);
		giftPromotionMapper.listGiftPromotionStoreId(productStoreId, request);
		List<GiftPromotion> retList = pagedResult.getResult();
		if (CollectionUtils.isEmpty(retList)) {
			return pagedResult;
		}
		List<String> promotionIds = retList.stream().map(GiftPromotion::getId).collect(Collectors.toList());
		List<GiftPromotionArea> findAreas = giftPromotionAreaMapper.listPromotionAreas(promotionIds);
		List<GiftPromotionGift> findGifts = giftPromotionGiftMapper.listPromotionGifts(promotionIds);
//		List<GiftPromotionProduct> findProducts = giftPromotionProductMapper.listPromotionProducts(promotionIds);
		List<AmountOrderInfo> orderInfoList = giftPromotionFlowingMapper.listGiftOrderInfo(promotionIds);
		for (GiftPromotion promotion : retList) {
			if (promotion.getExpireDate().getTime() < new Date().getTime()) {
				promotion.setPromotionStatus("N");
			}
			for (GiftPromotionArea area : findAreas) {
				if (area.getGiftPromotionId().equals(promotion.getId())) {
					if (promotion.getAreas() != null) {
						promotion.getAreas().add(area);
					} else {
						List<GiftPromotionArea> temps = Lists.newArrayList();
						temps.add(area);
						promotion.setAreas(temps);
					}
				}
			}
			for (GiftPromotionGift gift : findGifts) {
				if (gift.getGiftPromotionId().equals(promotion.getId())) {
					if (promotion.getGitfs() != null) {
						promotion.getGitfs().add(gift);
					} else {
						List<GiftPromotionGift> temps = Lists.newArrayList();
						temps.add(gift);
						promotion.setGitfs(temps);
					}
				}
			}
			//新增首单交易量
			for (AmountOrderInfo order : orderInfoList) {
				if (order.getPromotionId().equals(promotion.getId())) {
					promotion.setRealGiftNum(order.getGiftExcessTotal());
					promotion.setFirstOrderNum(order.getFirstOrderNum());
					promotion.setAvgAmount(String.valueOf(order.getAvgAmount()));
				}
			}
			
			
//			for (GiftPromotionProduct product : findProducts) {
//				if (product.getGiftPromotionId().equals(promotion.getId())) {
//					if (promotion.getProducts() != null) {
//						promotion.getProducts().add(product);
//					} else {
//						List<GiftPromotionProduct> temps = Lists.newArrayList();
//						temps.add(product);
//						promotion.setProducts(temps);
//					}
//				}
//			}
		}
		return pagedResult;
	}
	
	public List<String> validGiftPromotionProducts(String productStoreId, String giftPromotionId,
			List<String> productIds, Date startDate, Date endDate) {
		return giftPromotionMapper.validGiftPromotionProducts(productStoreId, giftPromotionId, startDate, endDate, productIds);
	}
	
	public GiftDeduction giftDeductionForOrder(GiftDeduction request) {
		logger.info("买赠活动订单下单扣减赠品入参：" + new Gson().toJson(request));
		if (CollectionUtils.isEmpty(request.getProducts())) {
			return null;
		}
		List<String> promitionIds = Lists.newArrayList();
		List<GiftDeductionProduct> productList = Lists.newArrayList();
		List<GiftPromotionGift> giftList = Lists.newArrayList(); //所有赠品活动赠品信息
		Map<String, Integer> surplusGiftNumMap = Maps.newHashMap(); //剩余扣减量
		Map<String, Integer> totalGiftNum = Maps.newHashMap(); //总扣减量
		Map<String, Double> totalGiftPrice = Maps.newHashMap(); //扣减赠品总价值
		for (GiftDeductionProduct product :request.getProducts()) {
			for (GiftDeductionGift gift : product.getGifts()) {
				if (!promitionIds.contains(gift.getPromotionId())) {
					promitionIds.add(gift.getPromotionId());
				}
			}
		}
		if (CollectionUtils.isNotEmpty(promitionIds)) {
			giftList = giftPromotionGiftMapper.listPromotionGifts(promitionIds);
		}
		//组数据
		for (GiftDeductionProduct product :request.getProducts()) {
				//重组赠品数据	
			    GiftDeductionProduct newProduct = new GiftDeductionProduct();
				newProduct.setOrderId(product.getOrderId());
				newProduct.setProductId(product.getProductId());
				newProduct.setProductName(product.getProductName());
				productList.add(newProduct);
			for (GiftDeductionGift gift : product.getGifts()) {
				  	StringBuilder sb = new StringBuilder();    
					String proAndGiftId = sb.append(gift.getPromotionId()).append("-").append(gift.getGifId()).toString();
					if (surplusGiftNumMap != null && surplusGiftNumMap.containsKey(proAndGiftId)) {
						resultGiftDeduction(gift, surplusGiftNumMap.get(proAndGiftId), proAndGiftId, gift.getPromotionId(),
								productList, surplusGiftNumMap, totalGiftNum, totalGiftPrice);
					} else {
						for (GiftPromotionGift promotionGift : giftList) {
							if (gift.getPromotionId().equals(promotionGift.getGiftPromotionId())
								&& gift.getGifId().equals(promotionGift.getGiftId())) {
								//剩余赠送数
								int surNum = promotionGift.getTotalAmount() - promotionGift.getExcessAmount();
								resultGiftDeduction(gift, surNum, proAndGiftId, gift.getPromotionId(),
									productList, surplusGiftNumMap, totalGiftNum, totalGiftPrice);
							}
						}
					}
					
			}
		}
		if (totalGiftNum == null) {
			return null;
		}
		List<GiftPromotionGift> promotionGiftList = Lists.newArrayList();
		//计算扣减
		for (Map.Entry<String, Integer> entry : totalGiftNum.entrySet()) {  
			   String key = entry.getKey();  
			   Integer value = entry.getValue(); 
			   String [] arr = key.split("-");
			   for (GiftPromotionGift gifts : giftList) {
				   if (gifts.getGiftId().equals(arr[1]) && gifts.getGiftPromotionId().equals(arr[0])) {
					   GiftPromotionGift promotionGift = new GiftPromotionGift();
					   promotionGift.setId(gifts.getId());	  
					   promotionGift.setExcessAmount(value + gifts.getExcessAmount());
					   promotionGiftList.add(promotionGift);
					   break;
				   }
			   }
		}
		//计算流水
		List<GiftPromotionFlowing> flows = Lists.newArrayList();
		IncrementIdCreator idCreator = new IncrementIdCreator();
		for (Map.Entry<String, Double> entry : totalGiftPrice.entrySet()) {  
			   String key = entry.getKey();  
			   Double price = entry.getValue();
			   GiftPromotionFlowing flowing = new GiftPromotionFlowing();
			   flowing.setCompanyId(request.getCompanyId());
			   flowing.setCompanyName(request.getCompanyName());
			   flowing.setId(idCreator.getNextIncrementId());
			   flowing.setAmountCut(String.valueOf(price));
			   flowing.setOrderAmount(request.getOrderAmount());
			   flowing.setOrderId(request.getOrderId());
			   flowing.setOrderTime(request.getOrderTime());
			   flowing.setPromotionId(key);
			   flows.add(flowing);
		}
		if (CollectionUtils.isEmpty(flows) && CollectionUtils.isEmpty(promotionGiftList)) {
			return null;
		}
		logger.info("买赠活动订单下单批量更新赠品数量组装数据：" + new Gson().toJson(promotionGiftList));
		giftPromotionGiftMapper.updateBatchPromotionGifts(promotionGiftList);
		giftPromotionFlowingMapper.insertGiftPromotionFlowing(flows);
		List<GiftDeductionProduct> returnList = productList.stream().
			filter(p -> CollectionUtils.isNotEmpty(p.getGifts())).collect(Collectors.toList());
		request.setProducts(returnList);
		logger.info("买赠活动订单下单扣减赠品返回值：" + new Gson().toJson(request));
		return request;
	}
	
	public void giftFallbackForOrder(List<GiftDeductionGift> gifts) {
		logger.info("买赠活动订单下单回退赠品入参：" + new Gson().toJson(gifts));
		List<String> promotionIds = gifts.stream().map(GiftDeductionGift::getPromotionId).collect(Collectors.toList());
		List<GiftPromotionGift> giftList = giftPromotionGiftMapper.listPromotionGifts(promotionIds);
		List<GiftPromotionFlowing> flowingList = giftPromotionFlowingMapper.gitGiftPromotionFlowingByOrderId(gifts);
		if (CollectionUtils.isEmpty(giftList) || CollectionUtils.isEmpty(flowingList)) {
			return;
		}
		
		//组装回退赠品数量
		List<GiftPromotionGift> promotionGiftList = Lists.newArrayList();
		for (GiftDeductionGift gift : gifts) {
			for (GiftPromotionFlowing flow : flowingList) {
				if (gift.getPromotionId().equals(flow.getPromotionId()) && gift.getOrderId().equals(flow.getOrderId())) {
					for (GiftPromotionGift promotion : giftList) {
						if (gift.getGifId().equals(promotion.getGiftId()) 
								&& gift.getPromotionId().equals(promotion.getGiftPromotionId())
								&& gift.getGiftAmount() <= promotion.getExcessAmount()) {
							   GiftPromotionGift promotionGift = new GiftPromotionGift();
							   promotionGift.setId(promotion.getId());	  
							   promotionGift.setExcessAmount(promotion.getExcessAmount() - gift.getGiftAmount());
							   promotionGiftList.add(promotionGift);
							   break;
						   }
					}
					break;
				}
			}
		}
		if (CollectionUtils.isNotEmpty(promotionGiftList)) {
			logger.info("买赠活动订单下单批量回退赠品数量组装数据：" + new Gson().toJson(promotionGiftList));
			giftPromotionGiftMapper.updateBatchPromotionGifts(promotionGiftList);
			giftPromotionFlowingMapper.deleteGiftPromotionFlowing(gifts);
		}
	}
	
	
	/**
	 * 
	 * resultGiftDeduction:(订单扣减数据组合).<br/>  
	 * @param gift					 赠品信息
	 * @param surplusGiftNum	 	赠品剩余数
	 * @param promotionAndGiftId 	活动和赠品id拼接成唯一标示
	 * @param promitionId 			活动id
	 * @param productResult 		返回订单结果
	 * @param surplusGiftNumMap  	剩余赠品数map
	 * @param totalNumMap 			赠送总数map
	 * @param totalGiftPrice 		赠品赠送总价格
	 * @author hongcheng.wu
	 * @date 2018年4月3日 下午8:16:59
	 */
	private void resultGiftDeduction(GiftDeductionGift gift, Integer surplusGiftNum, String promotionAndGiftId,
			String promitionId, List<GiftDeductionProduct> productResult, Map<String, Integer> surplusGiftNumMap, 
			Map<String, Integer> totalNumMap, Map<String, Double> totalGiftPrice) {
		    if (surplusGiftNum <= 0) {
		    	return;
		    }
			//剩余数量
			Integer surplusNum = 0;
			Integer totalNum = 0;
		    if (surplusGiftNum >= gift.getGiftAmount()) {
				surplusNum = surplusGiftNum - gift.getGiftAmount();
				totalNum = gift.getGiftAmount();
			} else {
				totalNum = surplusGiftNum;
			}
		    double giftValue = 0; 
		    if (gift.getGiftPrice() != null) {
		    	giftValue = gift.getGiftPrice();
		    }
		    //修改剩余量
		    surplusGiftNumMap.put(promotionAndGiftId, surplusNum);
		    //修改总扣减数(用于计算实际扣减量)
		    if (totalNumMap.containsKey(promotionAndGiftId)) {
		    	totalNumMap.put(promotionAndGiftId, totalNum + totalNumMap.get(promotionAndGiftId));
		    } else {
		    	totalNumMap.put(promotionAndGiftId, totalNum);
		    }
		    //修改赠品总价值(用于流水插入)
		    if (totalGiftPrice.containsKey(promitionId)) {
		    	totalGiftPrice.put(promitionId, totalGiftPrice.get(promitionId) + totalNum * giftValue);
		    } else {
		    	totalGiftPrice.put(promitionId, totalNum * giftValue);
		    }
		    //重置扣减数量
		    gift.setGiftAmount(totalNum);
		    for (GiftDeductionProduct product :productResult) {
		    	if (product.getProductId().equals(gift.getProductId())) {
		    		if (product.getGifts() != null) {
		    			product.getGifts().add(gift);
					} else {
						List<GiftDeductionGift> temps = Lists.newArrayList();
						temps.add(gift);
						product.setGifts(temps);
					}
		    	}
		    }
    }
	
	
	
	private void insertPromotionConfigs(GiftPromotion giftPromotion, IncrementIdCreator idCreator, User user, Date now) {
		if (CollectionUtils.isNotEmpty(giftPromotion.getProducts())) {
			for (GiftPromotionProduct product : giftPromotion.getProducts()) {
				product.setId(idCreator.getNextIncrementId());
				product.setGiftPromotionId(giftPromotion.getId());
				product.setCreatedBy(user.getUserLoginId());
				product.setCreatedStamp(now);
			}
			giftPromotionProductMapper.insertPromotionProducts(giftPromotion.getProducts());
		}
		if (CollectionUtils.isNotEmpty(giftPromotion.getGitfs())) {
			for (GiftPromotionGift gift : giftPromotion.getGitfs()) {
				gift.setId(idCreator.getNextIncrementId());
				gift.setGiftPromotionId(giftPromotion.getId());
				gift.setCreatedBy(user.getUserLoginId());
				gift.setCreatedStamp(now);
			}
			giftPromotionGiftMapper.insertPromotionGifts(giftPromotion.getGitfs());
		}
		if (CollectionUtils.isNotEmpty(giftPromotion.getAreas())) {
			for (GiftPromotionArea area : giftPromotion.getAreas()) {
				area.setId(idCreator.getNextIncrementId());
				area.setGiftPromotionId(giftPromotion.getId());
			}
			giftPromotionAreaMapper.insertPromotionAreas(giftPromotion.getAreas());
		}
	}
	
	private GiftPromotionUpdateRecord createUpdateRecord(GiftPromotion oldPromotion, GiftPromotion newPromotion,
			IncrementIdCreator idCreator, User user, Date now) {
		GiftPromotionUpdateRecord record = new GiftPromotionUpdateRecord();
		record.setId(idCreator.getNextIncrementId());
		record.setPromotionId(oldPromotion.getId());
		record.setUserLoginId(user.getUserLoginId());
		record.setUserLoginName(user.getUserName());
		record.setCreatedStamp(now);
		
		StringBuffer description = new StringBuffer();
		SimpleDateFormat simpleformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (!oldPromotion.getPromotionName().equals(newPromotion.getPromotionName())) {
			description.append(MessageFormat.format("活动名称 由 {0} 修改成 {1}；", oldPromotion.getPromotionName(), newPromotion.getPromotionName()));
		}
		if (!simpleformat.format(oldPromotion.getEffectDate()).equals(simpleformat.format(newPromotion.getEffectDate()))) {
			description.append(
					MessageFormat.format("活动开始时间 由 {0} 修改成 {1}；", simpleformat.format(oldPromotion.getEffectDate()),
							simpleformat.format(newPromotion.getEffectDate())));
		}
		if (!simpleformat.format(oldPromotion.getExpireDate()).equals(simpleformat.format(newPromotion.getExpireDate()))) {
			description.append(
					MessageFormat.format("活动结束时间 由 {0} 修改成 {1}；", simpleformat.format(oldPromotion.getExpireDate()),
							simpleformat.format(newPromotion.getExpireDate())));
		}
		if (!oldPromotion.getTargetPlatform().equals(newPromotion.getTargetPlatform())) {
			description.append(MessageFormat.format("活动平台 由 {0} 修改成 {1}；",
					GiftConfigValueEnum.getName(oldPromotion.getTargetPlatform()),
					GiftConfigValueEnum.getName(newPromotion.getTargetPlatform())));
		}
		if (!oldPromotion.getTargetCustomer().equals(newPromotion.getTargetCustomer())) {
			description.append(MessageFormat.format("活动对象 由 {0} 修改成 {1}；",
					GiftConfigValueEnum.getName(oldPromotion.getTargetCustomer()),
					GiftConfigValueEnum.getName(newPromotion.getTargetCustomer())));
		}
		if (oldPromotion.getAreas() == null) {
			oldPromotion.setAreas(Lists.newArrayList());
		}
		if (newPromotion.getAreas() == null) {
			newPromotion.setAreas(Lists.newArrayList());
		}
//		String areaChange = createAreaDiffDescription(oldPromotion.getAreas(), newPromotion.getAreas());
//		if (StringUtils.isNotBlank(areaChange)) {
//			description.append("修改活动城市：" + areaChange);
//		}
		if (GiftConfigValueEnum.AREA_LIMIT_DEFAULT.getIndex().equals(oldPromotion.getTargetArea())
				&& GiftConfigValueEnum.AREA_LIMIT_CUSTOM.getIndex().equals(newPromotion.getTargetArea())) {
			String des = MessageFormat.format("活动城市 由 {0} 修改成 {1}；",
					GiftConfigValueEnum.AREA_LIMIT_DEFAULT.getName(),
					GiftConfigValueEnum.AREA_LIMIT_CUSTOM.getName());
			des += createAreaDiffDescription(Lists.newArrayList(), newPromotion.getAreas());
			description.append(des);
			
		} else if (GiftConfigValueEnum.AREA_LIMIT_CUSTOM.getIndex().equals(oldPromotion.getTargetArea())
				&& GiftConfigValueEnum.AREA_LIMIT_DEFAULT.getIndex().equals(newPromotion.getTargetArea())) {
			String des = MessageFormat.format("活动城市 由 {0} 修改成 {1}；",
					GiftConfigValueEnum.AREA_LIMIT_CUSTOM.getName(),
					GiftConfigValueEnum.AREA_LIMIT_DEFAULT.getName());
			description.append(des);
		} else if (GiftConfigValueEnum.AREA_LIMIT_CUSTOM.getIndex().equals(newPromotion.getTargetArea())
				&& GiftConfigValueEnum.AREA_LIMIT_CUSTOM.getIndex().equals(oldPromotion.getTargetArea())) {
			String areaChange = createAreaDiffDescription(oldPromotion.getAreas(), newPromotion.getAreas());
			if (StringUtils.isNotBlank(areaChange)) {
				description.append("修改活动城市：" + areaChange);
			}
		}
		
		if (oldPromotion.getProducts() == null) {
			oldPromotion.setProducts(Lists.newArrayList());
		}
		if (newPromotion.getProducts() == null) {
			newPromotion.setProducts(Lists.newArrayList());
		}
		String productChange = createProductDiffDescription(oldPromotion.getProducts(), newPromotion.getProducts());
		if (StringUtils.isNotBlank(productChange)) {
			description.append("修改活动商品：" + productChange);
		}
		
		if (oldPromotion.getGitfs() == null) {
			oldPromotion.setGitfs(Lists.newArrayList());
		}
		if (newPromotion.getGitfs() == null) {
			newPromotion.setGitfs(Lists.newArrayList());
		}
		String giftChange = createGiftDiffDescription(oldPromotion.getGitfs(), newPromotion.getGitfs());
		if (StringUtils.isNotBlank(giftChange)) {
			description.append("修改活动赠品：" + giftChange);
		}
		
		if (StringUtils.isBlank(description.toString())) {
			return null;
		} else {
			record.setDescription(description.toString());
			return record;
		}
	}
	
	private String createAreaDiffDescription(List<GiftPromotionArea> oldAreas, List<GiftPromotionArea> newAreas) {
		String description = "";
		Map<String, String> geoMap = Maps.newHashMap();
		for (GiftPromotionArea area : oldAreas) {
			geoMap.put(area.getGeoId(), area.getGeoName());
		}
		for (GiftPromotionArea area : newAreas) {
			geoMap.put(area.getGeoId(), area.getGeoName());
		}
		
		List<String> removeArea = Lists.newArrayList();
		List<String> oldAreaIds = oldAreas.stream().map(GiftPromotionArea::getGeoId).collect(Collectors.toList());
		oldAreaIds.removeAll(newAreas.stream().map(GiftPromotionArea::getGeoId).collect(Collectors.toList()));
		if (oldAreaIds.size() > 0) {
			removeArea.addAll(oldAreaIds);
		}
		List<String> addArea = Lists.newArrayList();
		List<String> newAreaIds = newAreas.stream().map(GiftPromotionArea::getGeoId).collect(Collectors.toList());
		newAreaIds.removeAll(oldAreas.stream().map(GiftPromotionArea::getGeoId).collect(Collectors.toList()));
		if (newAreaIds.size() > 0) {
			addArea.addAll(newAreaIds);
		}
		
		if (addArea.size() != 0) {
			description += "新增城市：";
			for (String area : addArea) {
				if (geoMap.containsKey(area)) {
					description += geoMap.get(area) + "，";
				} else {
					description += area + "，";
				}
			}
			description  = description.substring(0, description.length() - 1);
			description += "；";
		}
		if (removeArea.size() != 0) {
			description += "删除城市：";
			for (String area : removeArea) {
				if (geoMap.containsKey(area)) {
					description += geoMap.get(area) + "，";
				} else {
					description += area + "，";
				}
			}
			description  = description.substring(0, description.length() - 1);
			description += "；";
		}
		
		return description;
	}
	
	private String createProductDiffDescription(List<GiftPromotionProduct> oldProducts, List<GiftPromotionProduct> newProducts) {
		String description = "";
		Map<String, String> productMap = Maps.newHashMap();
		for (GiftPromotionProduct product : oldProducts) {
			productMap.put(product.getProductId(), product.getInternalName());
		}
		for (GiftPromotionProduct product : newProducts) {
			productMap.put(product.getProductId(), product.getInternalName());
		}
		List<String> removeProduct = Lists.newArrayList();
		List<String> oldProductIds = oldProducts.stream().map(GiftPromotionProduct::getProductId).collect(Collectors.toList());
		oldProductIds.removeAll(newProducts.stream().map(GiftPromotionProduct::getProductId).collect(Collectors.toList()));
		if (oldProductIds.size() > 0) {
			removeProduct.addAll(oldProductIds);
		}
		List<String> addProduct = Lists.newArrayList();
		List<String> newProductIds = newProducts.stream().map(GiftPromotionProduct::getProductId).collect(Collectors.toList());
		newProductIds.removeAll(oldProducts.stream().map(GiftPromotionProduct::getProductId).collect(Collectors.toList()));
		if (newProductIds.size() > 0) {
			addProduct.addAll(newProductIds);
		}
		
		if (addProduct.size() != 0) {
			description += "新增商品：";
			for (String product : addProduct) {
				if (productMap.containsKey(product)) {
					description += productMap.get(product) + "，";
				} else {
					description += product + "，";
				}
			}
			description  = description.substring(0, description.length() - 1);
			description += "；";
		}
		if (removeProduct.size() != 0) {
			description += "删除商品：";
			for (String product : removeProduct) {
				if (productMap.containsKey(product)) {
					description += productMap.get(product) + "，";
				} else {
					description += product + "，";
				}
			}
			description  = description.substring(0, description.length() - 1);
			description += "；";
		}
		
		return description;
	}
	
	private String createGiftDiffDescription(List<GiftPromotionGift> oldProducts, List<GiftPromotionGift> newProducts) {
		String description = "";
		Map<String, String> productMap = Maps.newHashMap();
		for (GiftPromotionGift product : oldProducts) {
			productMap.put(product.getGiftId(), product.getGiftCode());
		}
		for (GiftPromotionGift product : newProducts) {
			productMap.put(product.getGiftId(), product.getGiftCode());
		}
		List<String> removeProduct = Lists.newArrayList();
		List<String> oldProductIds = oldProducts.stream().map(GiftPromotionGift::getGiftId).collect(Collectors.toList());
		oldProductIds.removeAll(newProducts.stream().map(GiftPromotionGift::getGiftId).collect(Collectors.toList()));
		if (oldProductIds.size() > 0) {
			removeProduct.addAll(oldProductIds);
		}
		List<String> addProduct = Lists.newArrayList();
		List<String> newProductIds = newProducts.stream().map(GiftPromotionGift::getGiftId).collect(Collectors.toList());
		newProductIds.removeAll(oldProducts.stream().map(GiftPromotionGift::getGiftId).collect(Collectors.toList()));
		if (newProductIds.size() > 0) {
			addProduct.addAll(newProductIds);
		}
		
		if (addProduct.size() != 0) {
			description += "新增赠品：";
			for (String product : addProduct) {
				if (productMap.containsKey(product)) {
					description += productMap.get(product) + "，";
				} else {
					description += product + "，";
				}
			}
			description  = description.substring(0, description.length() - 1);
			description += "；";
		}
		if (removeProduct.size() != 0) {
			description += "删除赠品：";
			for (String product : removeProduct) {
				if (productMap.containsKey(product)) {
					description += productMap.get(product) + "，";
				} else {
					description += product + "，";
				}
			}
			description  = description.substring(0, description.length() - 1);
			description += "；";
		}
		
		for (GiftPromotionGift oldGift : oldProducts) {
			for (GiftPromotionGift newGift : newProducts) {
				if (oldGift.getGiftCode().equals(newGift.getGiftCode())) {
					if (oldGift.getPerAmount() != newGift.getPerAmount()) {
						description += MessageFormat.format("赠品编码 {0} ，单笔赠送数量 由 {1} 修改为 {2}；", newGift.getGiftCode(),
								oldGift.getPerAmount(), newGift.getPerAmount());
					}
					if (oldGift.getTotalAmount() != newGift.getTotalAmount()) {
						description += MessageFormat.format("赠品编码 {0} ，赠送总数 由 {1} 修改为 {2}；", newGift.getGiftCode(),
								oldGift.getTotalAmount(), newGift.getTotalAmount());
					}
				}
			}
		}
		return description;
	}
	
	private List<GiftPromotion> filterGiftPromotion(List<String> giftPromotionIds, AmountPromotionQueryRequest queryRequest,
            List<DiscountRuleParam> ruleParams) {
        List<GiftPromotion> listGiftPromotion = giftPromotionMapper.listGiftPromotionByIds(giftPromotionIds);
        //用户平台登陆过滤
        List<GiftPromotion> listGiftPromotionFilterPlatform = Lists.newArrayList();
        for (GiftPromotion giftPromotion : listGiftPromotion) {
            if (giftPromotion.getTargetPlatform().equals(DiscountConfigValueEnum.PLATFORM_ALL.getIndex())) {
            	listGiftPromotionFilterPlatform.add(giftPromotion);
            } else {
                if (giftPromotion.getTargetPlatform().equals(queryRequest.getPlatform())) {
                	listGiftPromotionFilterPlatform.add(giftPromotion);
                }                
            }
        }
        if (CollectionUtils.isEmpty(listGiftPromotionFilterPlatform)) {
        	return listGiftPromotionFilterPlatform;
        }
        
        //用户类型过滤(交易和未交易)
        List<GiftPromotion> listGiftPromotionFilterTargetCustomer = Lists.newArrayList();
        for (GiftPromotion giftPromotion : listGiftPromotionFilterPlatform) {
            if (giftPromotion.getTargetCustomer().equals(DiscountConfigValueEnum.CUSTOMER_ALL.getIndex())) {
                 listGiftPromotionFilterTargetCustomer.add(giftPromotion);
            } else {
                 for (DiscountRuleParam ruleParam : ruleParams) {
                      if (giftPromotion.getProductStoreId().equals(ruleParam.getProductStoreId())
                                && giftPromotion.getTargetCustomer().equals(ruleParam.getCustomerType())) {
                           listGiftPromotionFilterTargetCustomer.add(giftPromotion);
                      }
                 }
            }
        }
        if (CollectionUtils.isEmpty(listGiftPromotionFilterTargetCustomer)) {
        	return listGiftPromotionFilterTargetCustomer;
        }
        
        //根据活动Id查找区域设定
        List<GiftPromotionArea> listGiftPromotionArea = giftPromotionAreaMapper.listPromotionAreas(giftPromotionIds);
        Map<String, List<String>> gpaListMap = Maps.newHashMap();
        //用户区域过滤
        List<GiftPromotion> listGiftPromotionFilterTargetArea = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(listGiftPromotionArea)) {
	        for (GiftPromotionArea giftPromotionArea : listGiftPromotionArea) {
	            if (gpaListMap.containsKey(giftPromotionArea.getGiftPromotionId())) {
	                 gpaListMap.get(giftPromotionArea.getGiftPromotionId()).add(giftPromotionArea.getGeoId());
	            } else {
	                 List<String> giftPromotionAreaList = Lists.newArrayList();
	                 giftPromotionAreaList.add(giftPromotionArea.getGeoId());
	                 gpaListMap.put(giftPromotionArea.getGiftPromotionId(), giftPromotionAreaList);
	            }
	        }
	        for (GiftPromotion giftPromotion : listGiftPromotionFilterTargetCustomer) {
	        	for (String key : gpaListMap.keySet()) {
	        		if (key.equals(giftPromotion.getId())) {
	        			giftPromotion.setAreaIds(gpaListMap.get(key));
	        		}
	        	}
	        }
	        for (GiftPromotion giftPromotion : listGiftPromotionFilterTargetCustomer) {
	            if (DiscountConfigValueEnum.AREA_LIMIT_CUSTOM.getIndex().equals(giftPromotion.getTargetArea())) {
	                 for (DiscountRuleParam ruleParam : ruleParams) {
	                	for (String geoId : ruleParam.getGeoIds()) {
	                		if (giftPromotion.getAreaIds().contains(geoId)) {
	                			if (!listGiftPromotionFilterTargetArea.contains(giftPromotion)) {
	                				listGiftPromotionFilterTargetArea.add(giftPromotion);
	                			}
	                		}
	                	}
	                 }
	            } else {
	                 listGiftPromotionFilterTargetArea.add(giftPromotion);
	            }
	        }
	        return listGiftPromotionFilterTargetArea;
        } else {
        	return listGiftPromotionFilterTargetCustomer;
        }
   }
}
